import { createRouter, createWebHashHistory } from 'vue-router'
import { routes } from './routes'

const router = createRouter({
    history: createWebHashHistory('' + import.meta.env.VITE_BASE_PATH),
    routes,
    // 路由跳转后，滚动条回到顶部
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition
        } else {
            return { top: 0 }
        }
    }
})

// 导航守卫处理重定向
router.beforeEach(async (to, from) => {
    if (to?.meta?.redirectUrl) {
        router.push({
            path: to?.meta?.redirectUrl,
            query: {},
            type: 'redirect'
        })
    }
    return true
})

router.onError((e) => {
    console.log('路由发生错误了', e)
})

export default router
